In [1]:
import matplotlib.pyplot as plt
import numpy as np
import random
import scipy as sp
# For presentation purposes only.
%matplotlib inline
In [2]:
a, b, c = 5, 7, 13
# Generate noisy data.
x = np.linspace(-25, 25, 51, True)
noise = [random.uniform(-100, 100) for i in x]
y = (a*x**2+b*x+c) + noise
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title("Noisy Parabola")
plt.grid()
In [3]:
from scipy.optimize import curve_fit
def f(x, a, b, c):
return a*x**2+b*x+c
initial_guess = (7, 4, 15)
param_values, covar = curve_fit(f, x, y, initial_guess)
print(param_values)
print(covar)
In [4]:
a, b, c = param_values
plt.scatter(x, y, marker='x')
plt.plot(x, f(x, a, b, c), c='r')
plt.xlabel('x')
plt.ylabel('y')
plt.title("Fitting Model to Data")
Out[4]: